import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/badge_icon.dart';
import 'package:casdon/core/utils/page_visibility_mixin.dart';
import 'package:casdon/modules/me/application/notification/user_center_notifier.dart';
import 'package:casdon/modules/me/application/notification/user_info_notifier.dart';
import 'package:casdon/modules/me/ui/widgets/circle_avatar_button.dart';
import 'package:casdon/modules/me/ui/widgets/defalut_style_cell.dart';
import 'package:casdon/modules/me/ui/widgets/icon_label_button.dart';
import 'package:casdon/modules/me/ui/widgets/vertical_title_card.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class MeScreen extends ConsumerStatefulWidget {
  const MeScreen({super.key});

  @override
  ConsumerState<MeScreen> createState() => _MeScreenState();
}

class _MeScreenState extends ConsumerState<MeScreen>
    with PageVisibilityMixin, WidgetsBindingObserver {
  bool _hasInitialized = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(userInfoNotifierProvider.notifier).fetchData();
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void onPageVisible() {
    ref.read(userCenterNotifierProvider.notifier).fetchData();
  }

  @override
  Widget build(BuildContext context) {
    final userCenterState = ref.watch(userCenterNotifierProvider);
    final userInfoState = ref.watch(userInfoNotifierProvider);
    final double headerHeight =
        MediaQuery.of(context).padding.top + kToolbarHeight;

    return buildPageVisibilityDetector(
      context,
      Stack(
        children: [
          Positioned.fill(
            child: Image.asset(
              Assets.images.screenHeader.path,
              fit: BoxFit.cover,
              alignment: Alignment.topCenter,
            ),
          ),
          Scaffold(
            backgroundColor: Colors.transparent,
            body: ListView(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              children: [
                SizedBox(height: headerHeight),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: _goMomentsScreen,
                  child: Row(
                    children: [
                      CircleAvatarButton(
                        imageUrl: userInfoState.userAvatars,
                        defaultImage: AssetImage(Assets.images.icAvatar.path),
                        size: 64.w,
                        onPressed: () => _goMomentsScreen(),
                      ),
                      SizedBox(width: 16.w),
                      Text(
                        (userInfoState.nickName != null &&
                                userInfoState.nickName!.isNotEmpty)
                            ? userInfoState.nickName!
                            : "凯度生活家",
                        style: context.textTheme.displayLarge?.copyWith(
                          color: context.customColorThemeNonNull.textColor1,
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 24.h),
                Row(
                  children: [
                    Expanded(
                      child: ValueTitleCard(
                        title: "动态",
                        value: userCenterState.topicTotal.toString(),
                        onTap: _goMomentsScreen,
                      ),
                    ),
                    Expanded(
                      child: ValueTitleCard(
                        title: "关注",
                        value: userCenterState.followTotal.toString(),
                        onTap: _goFlowScreen,
                      ),
                    ),
                    Expanded(
                      child: ValueTitleCard(
                        title: "粉丝",
                        value: userCenterState.fansTotal.toString(),
                        onTap: _goFansScreen,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 20.h),
                _buildServiceCenter(context, userCenterState),
                SizedBox(height: 10.h),
                DefaultStyleCell(
                  iconPath: Assets.images.icViewhistory.path,
                  titleLabel: "浏览记录",
                  onTap: _goViewHistoryScreen,
                ),
                SizedBox(height: 10.h),
                DefaultStyleCell(
                  iconPath: Assets.images.icSetting.path,
                  titleLabel: "设置",
                  onTap: () => _goSettingScreen(context),
                ),
                SizedBox(height: 10.h),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildServiceCenter(BuildContext context, dynamic userCenterState) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        children: [
          SizedBox(height: 16.h),
          Row(
            children: [
              BadgeIcon(imagePath: Assets.images.icServiceCenter.path),
              SizedBox(width: 10.w),
              Text(
                "服务中心",
                style: context.textTheme.headlineMedium?.copyWith(
                  color: context.customColorThemeNonNull.textColor1,
                ),
              ),
              const Spacer(),
              GestureDetector(
                onTap: () => _goServiceOrderList(context),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      "服务进度",
                      style: context.textTheme.bodyMedium?.copyWith(
                        color: context.customColorThemeNonNull.textColor3,
                      ),
                    ),
                    SizedBox(width: 6.w),
                    Icon(Icons.chevron_right, color: Colors.grey[400]),
                  ],
                ),
              ),
            ],
          ),
          SizedBox(height: 24.h),
          Row(
            children: [
              Expanded(
                child: IconLabelButton(
                  imagePath: Assets.images.icManual.path,
                  label: "使用手册",
                  onTap: () => _goManualScreen(context),
                ),
              ),
              Expanded(
                child: IconLabelButton(
                  imagePath: Assets.images.icServicePolicy.path,
                  label: "服务政策",
                  onTap: () => _goServicePolicyScreen(context),
                ),
              ),
              Expanded(
                child: IconLabelButton(
                  imagePath: Assets.images.icRepair.path,
                  label: "报装报修",
                  onTap: () => _goServicePostScreen(context),
                ),
              ),
              Expanded(
                child: IconLabelButton(
                  imagePath: Assets.images.icFeedback.path,
                  label: "意见反馈",
                  onTap: () => {_goFeedBackScreen(context)},
                ),
              ),
            ],
          ),
          SizedBox(height: 24.h),
        ],
      ),
    );
  }

  void _goMomentsScreen() {
    LifeSelfHomeRoute().push(context);
  }

  void _goFlowScreen() {
    FlowerListRoute().push(context);
  }

  void _goFansScreen() {
    FansListRoute().push(context);
  }

  void _goFeedBackScreen(BuildContext context) {
    FeedbackPostRoute().push(context);
  }

  void _goViewHistoryScreen() {
    BrowsingHistoryRoute().push(context);
  }

  void _goServiceOrderList(BuildContext context) =>
      ServiceOrderListRoute().push(context);
  void _goManualScreen(BuildContext context) =>
      WebPageRoute(url: CommonConfig.use_manual, title: '').push(context);
  void _goServicePolicyScreen(BuildContext context) =>
      WebPageRoute(url: CommonConfig.service_policy, title: '').push(context);
  void _goServicePostScreen(BuildContext context) =>
      ServiceOrderPostRoute().push(context);
  void _goSettingScreen(BuildContext context) => MeSettingRoute().push(context);
  void _handleAvatarClick(BuildContext context) => MeInfoRoute().push(context);
}
